<template>
  <div class="detail-wrapper">
    <a-card :bordered="true" style="margin: 5px;">
      <a-button type="primary" icon="ios-arrow-back" v-on:click="backToUserList">返回用户明细</a-button>
      <span style="margin-left: 15px;">基于用户分群，从个体层面研究用户行为序列，深入洞察用户行为动机。</span>
    </a-card>
    <a-row>
      <a-col span="8">
        <a-card :bordered="true" style="margin: 5px;" title="用户档案">
          <a-table :columns="propertyColumns" :data-source="propertyData" rowKey="name" :pagination="false" bordered></a-table>
        </a-card>
      </a-col>
      <a-col span="16">
        <a-card style="margin: 5px;">
          <a-tabs default-active-key="userTag">
            <a-tab-pane key="userTag" tab="用户标签">
              <a-card class="category-wrapper" :bordered="true" v-for="category in userTagList" :key="category.categoryName">
                <p slot="title">{{category.categoryName}}</p>
                <a-row>
                  <a-col :md="12" :lg="8" :xl="6" :xxl="4" v-for="(item, index) in category.items" :key="index">
                    <div class="tag-wrapper">
                      <p class="tag-name">{{item.name}}</p>
                      <p class="tag-value">{{item.value}}</p>
                    </div>
                  </a-col>
                </a-row>
              </a-card>
            </a-tab-pane>
            <a-tab-pane key="userBehavior" tab="用户行为" force-render>
              <UserEventReport v-bind:user-id="userId" v-bind:datasource-id="datasourceId" v-bind:group-id="groupId"></UserEventReport>
            </a-tab-pane>
          </a-tabs>

        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>

import {getUserDetailInfoApi, queryUserTagApi} from "@/api/userDetails";
import {mapActions} from "vuex";
import {isEmptyString} from "@/utils/util";
import UserEventReport from "@/views/userProfile/userDetail/components/UserEventReport";

const propertyColumns = [
  {
    title: '用户属性',
    dataIndex: 'name',
  },
  {
    title: '值',
    dataIndex: 'value',
  }
]

export default {
  name: "UserDetail",
  components: {UserEventReport},
  data(){
    return {
      propertyColumns,
      userId: null,
      groupId: null,
      datasourceId: null,
      userProperties: [],
      propertyData: [],
      userTagList: []
    }
  },
  computed: {},
  methods: {
    ...mapActions('analyseType', ['getMetaUserProperties']),
    initPageData(){
      this.getUserProperties();
      this.getUserInfo();
      this.loadUserTags();
    },
    buildUserInfoTableData(){
      let data = [];
      let groups = [];
      if (!this.userInfo){
        return
      }
      for(let i = 0; i < this.userProperties.length; i++) {
        if(this.userInfo.hasOwnProperty(this.userProperties[i].name)) {
          if(this.userProperties[i].name.startsWith("cg_") && this.userInfo[this.userProperties[i].name]) {
            groups.push(this.userProperties[i].displayName);
          } else {
            data.push({
              name: this.userProperties[i].displayName,
              value: this.userInfo[this.userProperties[i].name]
            })
          }
        }
      }
      data.unshift({
        name: '用户分群',
        value: groups.join(",")
      });
      this.propertyData = data;
    },
    getUserInfo: function() {
      if (!this.userId || this.groupId === null){
        return
      }
      getUserDetailInfoApi(this.userId,{groupId: this.groupId}).then(response => {
        if (response.code === 0) {
          this.userInfo = response.data;
          this.buildUserInfoTableData();
        }
      }).catch(error => {
          console.error(error);
      }).finally(() => {});
    },
    getUserProperties() {
      this.getMetaUserProperties(this.datasourceId).then(res=>{
        this.userProperties = res.filter(property => {
          return !property.name.startsWith("ut_");
        });
      }).catch(err=>{
        console.error(err)
        this.$message.error('用户属性获取失败，原因：' + err)
      })
    },
    loadUserTags() {
      queryUserTagApi(this.userId,{groupId: this.groupId}).then(res => {
        if (res && res.code === 0){
          this.userTagList = res.data.data
        }else {
          this.$message.error('用户标签数据加载失败，原因：' + res.msg)
        }
      }).catch(err => {
        console.error(err)
        this.$message.error('用户标签数据加载失败，原因：' + err)
      })
    },
    backToUserList(){
      this.$router.push({
        name: 'UserDetailList',
        query: {user_group_id: this.groupId}
      });
    }
  },
  mounted() {
    this.initPageData()
  },
  created() {
    const uid = this.$route.query.user_id
    const ug = this.$route.query.user_group_id
    const ds = this.$route.query.datasource_id
    if (!isEmptyString(uid) && !isEmptyString(ug) && !isEmptyString(ds)){
      this.groupId = Number(ug)
      this.userId = uid
      this.datasourceId = Number(ds)
    }
  }
}
</script>

<style scoped>
.detail-wrapper{
  width: 100%;
  height: 100%;
}

.category-wrapper {
  margin: 15px 5px 5px 5px;

}

.category-wrapper>>>.ant-card-head{
  background-color: #f8f8f9;
}

.category-wrapper>>>.ivu-card-body {
  padding-top: 0;
  padding-bottom: 15px;
}

.ant-card-head-title p{
  margin-bottom: 0;
}

.tag-wrapper {
  margin-top: 15px;
}

.tag-name {
  color: black;
  font-weight: bolder;
  font-size: 14px;
}
</style>
